#!/bin/bash
# Setup script for Cloud Printer BLE service permissions

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}This script must be run as root${NC}" 
   exit 1
fi

echo -e "${GREEN}Setting up Cloud Printer BLE service permissions...${NC}"

# Create system user for BLE service
echo "Creating ble-service user..."
if id "ble-service" &>/dev/null; then
    echo -e "${YELLOW}User ble-service already exists${NC}"
else
    useradd -r -s /bin/false -d /nonexistent -c "Cloud Printer BLE Service" ble-service
    echo -e "${GREEN}Created ble-service user${NC}"
fi

# Add user to bluetooth group
echo "Adding ble-service to bluetooth group..."
usermod -a -G bluetooth ble-service
echo -e "${GREEN}Added to bluetooth group${NC}"

# Install PolicyKit rules
echo "Installing PolicyKit rules..."
POLKIT_DIRS="/etc/polkit-1/rules.d /usr/share/polkit-1/rules.d"
INSTALLED=false

for DIR in $POLKIT_DIRS; do
    if [ -d "$DIR" ]; then
        cp polkit/50-cloud-printer-ble.rules "$DIR/"
        chmod 644 "$DIR/50-cloud-printer-ble.rules"
        echo -e "${GREEN}Installed PolicyKit rules to $DIR${NC}"
        INSTALLED=true
        break
    fi
done

if [ "$INSTALLED" = false ]; then
    echo -e "${RED}Could not find PolicyKit rules directory${NC}"
    echo "Please manually copy polkit/50-cloud-printer-ble.rules to your PolicyKit rules directory"
fi

# Update systemd service file if it exists
SYSTEMD_FILE="/etc/systemd/system/cloud-printer-ble.service"
if [ -f "$SYSTEMD_FILE" ]; then
    echo "Updating systemd service file..."
    
    # Check if User is already set
    if grep -q "^User=" "$SYSTEMD_FILE"; then
        sed -i 's/^User=.*/User=ble-service/' "$SYSTEMD_FILE"
    else
        # Add User directive after [Service] section
        sed -i '/^\[Service\]/a User=ble-service' "$SYSTEMD_FILE"
    fi
    
    # Check if Group is already set
    if grep -q "^Group=" "$SYSTEMD_FILE"; then
        sed -i 's/^Group=.*/Group=bluetooth/' "$SYSTEMD_FILE"
    else
        sed -i '/^\[Service\]/a Group=bluetooth' "$SYSTEMD_FILE"
    fi
    
    # Add capabilities if not present
    if ! grep -q "^CapabilityBoundingSet=" "$SYSTEMD_FILE"; then
        sed -i '/^\[Service\]/a CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW' "$SYSTEMD_FILE"
        sed -i '/^\[Service\]/a AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW' "$SYSTEMD_FILE"
    fi
    
    # Reload systemd
    systemctl daemon-reload
    echo -e "${GREEN}Updated systemd service file${NC}"
else
    echo -e "${YELLOW}Systemd service file not found at $SYSTEMD_FILE${NC}"
    echo "Please update your service file to run as ble-service user"
fi

# Test PolicyKit permissions
echo "Testing PolicyKit permissions..."
POLKIT_TEST=$(sudo -u ble-service dbus-send --system --print-reply \
    --dest=org.freedesktop.PolicyKit1 \
    /org/freedesktop/PolicyKit1/Authority \
    org.freedesktop.PolicyKit1.Authority.CheckAuthorization \
    2>&1 || true)

if [[ "$POLKIT_TEST" == *"error"* ]]; then
    echo -e "${YELLOW}Could not test PolicyKit permissions${NC}"
else
    echo -e "${GREEN}PolicyKit is configured${NC}"
fi

# Create required directories with proper permissions
echo "Creating required directories..."
DIRS="/var/lib/cloud-printer /var/log/cloud-printer /var/run/cloud-printer"
for DIR in $DIRS; do
    if [ ! -d "$DIR" ]; then
        mkdir -p "$DIR"
        chown ble-service:bluetooth "$DIR"
        chmod 750 "$DIR"
        echo -e "${GREEN}Created $DIR${NC}"
    else
        chown ble-service:bluetooth "$DIR"
        chmod 750 "$DIR"
        echo -e "${YELLOW}Updated permissions for $DIR${NC}"
    fi
done

echo -e "${GREEN}Permission setup complete!${NC}"
echo ""
echo "Next steps:"
echo "1. Restart PolicyKit: systemctl restart polkit"
echo "2. If using systemd service: systemctl restart cloud-printer-ble"
echo "3. Check logs: journalctl -u cloud-printer-ble -f"